package com.wxh.jwt.controller;

import com.wxh.jwt.annotation.UserLoginToken;
import com.wxh.jwt.common.RedisConstant;
import com.wxh.jwt.common.ResponseInfo;
import com.wxh.jwt.model.User;
import com.wxh.jwt.service.TokenService;
import com.wxh.jwt.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: UserController
 * @Description: 用户控制器
 * @Author wxh
 * @Date: 2020/5/28 14:54
 * @Version V1.0.0
 * @Since 1.8
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     *  登录
     * @param user
     * @return ResponseInfo
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseInfo login(@RequestBody User user){
        LOGGER.debug("进入login方法");
        ResponseInfo result = new ResponseInfo();
        User userDb = userService.findUserByUserName(user.getUserName());
        if(userDb == null){
            result.setMsg("登录失败，用户姓名不存在");
        }else{
            if(!userDb.getPassword().equals(user.getPassword())){
                result.setMsg("登录失败，用户密码错误");
            }else{
                String token  = redisTemplate.opsForValue().get(RedisConstant.TOKEN_KEY+userDb.getUserId());
                if(StringUtils.isEmpty(token)){
                    // 根据用户信息创建一个token
                    token = tokenService.createToken(userDb);
                    // 存入redis
                    redisTemplate.opsForValue().set(RedisConstant.TOKEN_KEY+userDb.getUserId(), token, RedisConstant.EXPIRE_TIME, TimeUnit.SECONDS);
                }

                Map<String,Object> map = new HashMap<>(10);
                map.put("token",token);
                map.put("user",userDb);
                result.setMsg("已经生成token");
                result.setData(map);
            }
        }
        return result;
    }

    /**
     *  登录成功后，获取信息
     * @return ResponseInfo
     */
    @UserLoginToken
    @RequestMapping(value = "/getMsg", method = RequestMethod.POST)
    public ResponseInfo getMsg(){
        ResponseInfo result = new ResponseInfo();
        result.setMsg("您已经token验证了");
        return result;
    }
}
